
import paho.mqtt.client as mqtt
import uuid
import atexit
import base64

def on_connect(client,userdata,flags,rc):
    print("Connected with result code:"+str(rc))

def  MqttClient(topic,ip="127.0.0.1",port=1883,clientId="uuid",username="",password="",qos=1):
    def call(func):
        def wrapper():
            id = clientId
            if(id == "uuid"):
                id = str(uuid.uuid1())

            client = mqtt.Client(id)
            client.on_connect = on_connect
            def on_message(client,userdata,msg):
                msg.payload = base64.decodebytes(msg.payload)
                func(client,userdata,msg)
            client.on_message = on_message
            if(username != "") :
                client.username_pw_set(username,password)
            client.connect(ip,port,600)
            client.subscribe(topic,qos=1)
            @atexit.register
            def close():
                client.disconnect()

            client.loop_forever()
        return wrapper
    return call

def mqtt_sender(topic,message,ip="127.0.0.1",port=1883,clientId="uuid",username="",password="",qos=1,retain=false):
    id = clientId
    if(id == "uuid"):
        id = str(uuid.uuid1())
    client = mqtt.Client(id)
    client.on_connect = on_connect
    if(username != ""):
        client.username_pw_set(username,password)
    client.connect(ip,int(port),600)
    message = base64.encodebytes(message.encode("UTF-8")).decode()
    client.publish(topic,payload=message,qos=qos,retain=retain)
    client.disconnect()